<?php
// +----------------------------------------------------------------------
// |     【BillMain】Service服务类
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\common\service;

use think\facade\Request;
use app\common\model\BillMain as M;
use app\common\model\DealMain as D_M;
use app\common\validate\BillMain as V;

class BillMain{
    // 添加
    public static function goAdd($data){
        //验证
        $validate = new V;
        if(!$validate->scene('add')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
			$data=self::dataFormat($data,'add');
            M::create($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
    
    // 编辑
    public static function goEdit($data,$id){
    	$where = is_array($id) ? $id : ['id'=>$id];
        //验证
        $validate = new V;
        if(!$validate->scene('edit')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
			$data=self::dataFormat($data,'edit');
             M::update($data,$where);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 状态
    public static function goStatus($data,$id){
        $model = is_array($id) ? M::where($id)->find() : M::find($id);
        if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
        try{
            $model->save($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 删除
    public static function goRemove($id){
	$model = is_array($id) ? M::where($id)->find() : M::find($id);
        if ($model->isEmpty()) return ['msg'=>'数据不存在','code'=>201];
        try{
           $model->delete();
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 批量删除
    public static function goBatchRemove($ids){
        if (!is_array($ids)) return ['msg'=>'数据不存在','code'=>201];
		$model = M::where($ids)->select();
        try{
            $model->delete();
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 获取列表
    public static function goRecycle($where = []){
        if (Request::isPost()){
            $ids = Request::param('ids');
			$where[]=['id','in',$ids];
            if (!is_array($ids)) return ['msg'=>'参数错误','code'=>'201'];
            try{
                if(Request::param('type')){
                    $data = M::onlyTrashed()->where($where)->select();
                    foreach($data as $k){
                        $k->restore();
                    }
                }else{
                    M::destroy($ids,true);
                }
            }catch (\Exception $e){
                return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
            }
            return ['msg'=>'操作成功'];
        }
        //按用户名
        
        $limit = I('get.limit/d');
        
               //按收支项目查找
               if ($name = input("name")) {
                   $where[] = ["name", "like", "%" . $name . "%"];
               }
        $list = M::onlyTrashed()->where($where)->paginate($limit);
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }
	
	//修改某个参数
	public static function setFieldValue($data,$where=[]){
		if(empty($where)){
			$model =  M::find($data['id']);
		}else{
			$model = M::where($where)->find();
		}
		if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
		try{
		    $model->save([
		        $data['field'] => $data['value'],
		    ]);
			return ['msg'=>'操作成功'];
		}catch (\Exception $e){
		    return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
		}
	}
	
	/**
	 * 更新订单收入利润到收支表
	 */
	public static function up_bill($ids,$uuid=0){
		if(!is_array($ids)) $ids=[$ids];
		$deal_list=D_M::where([['id','in',$ids],['uuid','=',$uuid]])->select();
		if($deal_list->isEmpty()){				//订单不存在，删除相关的收支表
			$res = M::where([['did','in',$ids],['uuid','=',$uuid]])->delete();
			return false;
		}
		//循环更新收支情况
		foreach ($deal_list as $deal){
			$id=$deal['id']??0;
			$bill=M::where(['did'=>$id,'uuid'=>$uuid])->find();
			if($deal['status']==1){
				$profit=$deal['total']-$deal['cost']-$deal['poundage']-$deal['freight'];			//利润
				$data=[
					'type'=>$profit>=0?1:0,
					'money'=>$profit,
					'remark'=>$deal['number'].' 订单',
					'status'=>1,
				];
				$data['remark'].=$profit>=0?'收入':'亏损';
				if($bill==''){				//没记录添加
					//获取订单的信息
					$deal_number=D_M::where('id',$id)->value('number');
					$data['name']='销售营收';
					$data['year']=date('Y',$deal['ocreate_time']);
					$data['month']=date('m',$deal['ocreate_time']);
					$data['day']=date('d',$deal['ocreate_time']);
					$data['create_time']=$deal['ocreate_time'];
					$data['did']=$id;
					$data['deal_number']=$deal_number;
					$data['uuid']=$uuid;
					M::insert($data);
				}else{						//有记录判断是否更新
					if($bill['money']!=$profit || $bill['status']==0 || $bill['create_time']!=$deal['ocreate_time']){	//没变化的数值不更新
						if($bill['create_time']!=$deal['ocreate_time']){
							$data['year']=date('Y',$deal['ocreate_time']);
							$data['month']=date('m',$deal['ocreate_time']);
							$data['day']=date('d',$deal['ocreate_time']);
							$data['create_time']=$deal['ocreate_time'];
						}
						M::where(['id'=>$bill['id'],'uuid'=>$uuid])->save($data);
					}
				}
			}else if($deal['status']==0){
				if($bill!=''){
					M::where(['id'=>$bill['id'],'uuid'=>$uuid])->save([
						'status'=>0,
						'money'=>0,
						'remark'=>$deal['number'].' 订单',
					]);
				}
			}else if($deal['status']==2){
				if($bill!=''){
					M::where(['id'=>$bill['id'],'uuid'=>$uuid])->save([
						'status'=>0,
						'money'=>0,
						'remark'=>$deal['number'].' 订单退款',
					]);
				}
			}
		}
	}
	
	
	// 预处理添加和修改的数据
	public static function dataFormat($data,$type='add'){
		
		if($type == 'add'){					//添加时才处理
			
		}else if($type == 'edit'){			//修改时才处理
			
		}
		// 无论修改还是添加都处理
		$data['create_time']=strtotime($data['create_time']);
		$data['year']=date('Y',$data['create_time']);
		$data['month']=date('m',$data['create_time']);
		$data['day']=date('d',$data['create_time']);
		return $data;
	}
}
